
package bigdata;

import backtype.storm.Config;
import backtype.storm.topology.OutputFieldsDeclarer;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;

import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;

import java.util.HashMap;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class InputSpout extends BaseRichSpout {
    public static Logger LOG = LoggerFactory.getLogger(InputSpout.class);
    boolean _isDistributed;
    SpoutOutputCollector _collector;

    public InputSpout() {
        this(true);
    }

    public InputSpout(boolean isDistributed) {
        _isDistributed = isDistributed;
    }
        
    public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
        _collector = collector;
    }
    
    public void close() {
        
    }
        
    public void nextTuple() {
       
        BufferedReader reader;
		try {
			reader = new BufferedReader(new FileReader(SimulationMain.logPath));
	
        String line = null;
        
        while ((line = reader.readLine()) != null) {
        	Utils.sleep(1000);  
        	SimulationMain.gui.addStringToLog(line);
        	_collector.emit(new Values(line));
        }
        _collector.emit(new Values("end"));
        Utils.sleep(10000);  
        
    } catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
        
		
    }
    
    public void ack(Object msgId) {

    }

    public void fail(Object msgId) {
        
    }
    
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("word"));
    }

    @Override
    public Map<String, Object> getComponentConfiguration() {
        if(!_isDistributed) {
            Map<String, Object> ret = new HashMap<String, Object>();
            ret.put(Config.TOPOLOGY_MAX_TASK_PARALLELISM, 1);
            return ret;
        } else {
            return null;
        }
    }    
}